package com.mojawa.mj_util.gps

import android.content.Context
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Bundle
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData

class GpsSignalMonitor(private val context: Context) {

    // 使用 MutableLiveData 持有当前信号状态
    private val _currentSignalStrength = MutableLiveData<GpsSignalStrength>()
    val currentSignalStrength: LiveData<GpsSignalStrength> = _currentSignalStrength

    private lateinit var locationManager: LocationManager

    // 定义监听器来获取 GPS 位置更新
    private val locationListener = object : LocationListener {
        override fun onLocationChanged(location: Location) {
            updateSignalStrength(location)
        }

        override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {}
        override fun onProviderEnabled(provider: String) {}
        override fun onProviderDisabled(provider: String) {
            _currentSignalStrength.postValue(GpsSignalStrength.NO_SIGNAL)
        }
    }

    // 启动 GPS 信号监控
    fun startMonitoring() {
        locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager

        try {
            locationManager.requestLocationUpdates(
                LocationManager.GPS_PROVIDER,
                1000L,
                0f,
                locationListener
            )
        } catch (e: SecurityException) {
            e.printStackTrace()
        }
    }

    // 停止 GPS 信号监控
    fun stopMonitoring() {
        locationManager.removeUpdates(locationListener)
    }

    // 更新信号强度并通知观察者
    private fun updateSignalStrength(location: Location) {
        val signalStrength = when (location.accuracy.toInt()) {
            in 1..10 -> GpsSignalStrength.STRONG
            in 11..50 -> GpsSignalStrength.WEAK
            else -> GpsSignalStrength.NO_SIGNAL
        }

        // 更新 LiveData 的值
        _currentSignalStrength.postValue(signalStrength)
    }
}